package com.techsoul.module.pms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.exception.BusinessException;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.CustomerConsigneeDeliveryAddressMapper;
import com.techsoul.module.basic.mapper.CustomerConsigneeMapper;
import com.techsoul.module.basic.mapper.CustomerMapper;
import com.techsoul.module.basic.mapper.WarehouseMapper;
import com.techsoul.module.basic.pojo.entity.Customer;
import com.techsoul.module.basic.pojo.entity.CustomerConsignee;
import com.techsoul.module.basic.pojo.entity.CustomerConsigneeDeliveryAddress;
import com.techsoul.module.basic.pojo.entity.Warehouse;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.goods.mapper.SkuMapper;
import com.techsoul.module.goods.pojo.vo.SkuVo;
import com.techsoul.module.order.pojo.entity.SalesOrder;
import com.techsoul.module.order.pojo.vo.SalesOrderItemVo;
import com.techsoul.module.pms.enmus.MaterialBaseOnEnum;
import com.techsoul.module.pms.enmus.WmsInStatusEnum;
import com.techsoul.module.pms.mapper.*;
import com.techsoul.module.pms.pojo.entity.TWhWarehouseCustomerMaterial;
import com.techsoul.module.pms.pojo.entity.TbWmsMaterialInLocation;
import com.techsoul.module.pms.pojo.entity.TbWmsMaterialReceipt;
import com.techsoul.module.pms.pojo.entity.TbWmsMaterialReceiptLine;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialDeliverySaveParam;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialReceiptLineSaveParam;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialReceiptSaveParam;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialReceiptSearchParam;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialReceiptVo;
import com.techsoul.module.pms.service.IBmsAllGeneralSeqTabService;
import com.techsoul.module.pms.service.ITbWmsMaterialReceiptLineService;
import com.techsoul.module.pms.service.ITbWmsMaterialReceiptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 入库计划 Service实现
 *
 * @author liuen
 * @date 2022-01-25
 */
@Service
@Transactional(readOnly = true)
public class TbWmsMaterialReceiptServiceImpl implements ITbWmsMaterialReceiptService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TbWmsMaterialReceiptMapper mapper;
    @Autowired
    private TbWmsMaterialReceiptLineMapper tbWmsMaterialReceiptLineMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private TbWmsMaterialInLocationMapper tbWmsMaterialInLocationMapper;

    @Autowired
    private ITbWmsMaterialReceiptLineService iTbWmsMaterialReceiptLineService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private TWhWarehouseCustomerMaterialMapper tWhWarehouseCustomerMaterialMapper;
    @Autowired
    private CustomerConsigneeDeliveryAddressMapper customerConsigneeDeliveryAddressMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private CustomerConsigneeMapper customerConsigneeMapper;

    @Autowired
    private TbUserWarehouseManagerMapMapper tbUserWarehouseManagerMapMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IBmsAllGeneralSeqTabService tBmsAllGeneralSeqTabService;
    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(TbWmsMaterialReceiptSaveParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        TbWmsMaterialReceipt entity = new TbWmsMaterialReceipt();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    @Transactional(readOnly = false)
    @Override
    public String addNewVehicleReceipt(TbWmsMaterialReceiptSaveParam params){
        // 收货人编码为空时，新增收货人
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String warehouseId = "";
        CustomerConsignee customerConsignee = null;
        if(StringUtils.isNull(params.getCustomerNo())) {
            String customerNo = this.generateCustomer(params,sysUser.getId());
            params.setCustomerNo(customerNo);
        }

        if(!StringUtils.isNull(params.getItemList().get(0).getConsigneeNo())) {
            customerConsignee = this.customerConsigneeMapper.selectById(params.getItemList().get(0).getConsigneeNo());
            if(customerConsignee==null){
                customerConsignee= this.generateConsigneeId(params,sysUser.getId(),params.getCustomerNo());
                params.getItemList().get(0).setCustomerNo(customerConsignee.getId());
                params.getItemList().get(0).setConsigneeName(customerConsignee.getConsigneeName());
            }
            params.getItemList().get(0).setConsigneeName(customerConsignee.getConsigneeName());
            //查询收货人地址是否存在（如果不存在就新建一个地址跟仓库）
            CustomerConsigneeDeliveryAddress ccda= this.customerConsigneeDeliveryAddressMapper.findByCustCodeAndAddress(params.getItemList().get(0).getConsigneeAddress(),params.getItemList().get(0).getConsigneeNo());

            if(ccda==null){
                warehouseId = this.generateConsigneeWarehouse(params,sysUser.getId(),customerConsignee);
                ccda= this.generateConsigneeDeliveryAddress(params,sysUser.getId(),params.getItemList().get(0).getConsigneeNo(),warehouseId);
            }else{
                warehouseId = ccda.getWarehouseCode();
            }
        }else {

            customerConsignee = this.generateConsigneeId(params,sysUser.getId(),params.getCustomerNo());
            params.getItemList().get(0).setCustomerNo(customerConsignee.getId());
            params.getItemList().get(0).setConsigneeName(customerConsignee.getConsigneeName());
            //查询收货人地址是否存在（如果不存在就新建一个地址跟仓库）
            CustomerConsigneeDeliveryAddress ccda= this.customerConsigneeDeliveryAddressMapper.findByCustCodeAndAddress(params.getItemList().get(0).getConsigneeAddress(),customerConsignee.getId());

            if(ccda==null){
                warehouseId = this.generateConsigneeWarehouse(params,sysUser.getId(),customerConsignee);
                ccda=  this.generateConsigneeDeliveryAddress(params,sysUser.getId(),customerConsignee.getId(),warehouseId);
            }else{
                warehouseId =ccda.getWarehouseCode();
            }

        }

        params.setCustomerNo(sysUser.getCustomerId());
        params.setCustomerName(sysUser.getCustomerId());

        // 新增运单主表信息
        if(StringUtils.isNull(params.getOrderNo())){
            String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialReceipt");
            params.setOrderNo("R".concat(orderNo));
        }

        params.setSiteCode(sysUser.getSite())
                .setStatus(WmsInStatusEnum.created.getValue());




        String receiptId = this.insert(params);

        // 新增运单明细信息
         List<TbWmsMaterialReceiptLine> tbWmsMaterialReceiptLines= insertItem(params, receiptId,sysUser);
        //新增库存信息
        tbWmsMaterialReceiptLines = insertMaterialInLocation(tbWmsMaterialReceiptLines,sysUser,params);


        return "success";
    }

    //生成仓库
    private String generateConsigneeWarehouse(TbWmsMaterialReceiptSaveParam params, String userId, CustomerConsignee customerConsignee) {
        Warehouse warehouse = new Warehouse();
        String [] str = params.getItemList().get(0).getDestination().split(",");
        warehouse.setId(idWorker.nextId() + "").preInsert(userId);
        warehouse.setOrgId(customerConsignee.getId());
        warehouse.setWarehouserCode("cosi".concat(warehouse.getId()));
        warehouse.setWarehouserName(customerConsignee.getConsigneeName().concat("卸货库"));
        warehouse.setWarehouseType("consignee");
        warehouse.setProvince(str[0]);
        warehouse.setCity(str[1]);
        warehouse.setDistrict(str[2]);
        warehouse.setAddress(params.getItemList().get(0).getConsigneeAddress());
        this.warehouseMapper.insert(warehouse);
        return warehouse.getId();
    }

    //生成地址
    private CustomerConsigneeDeliveryAddress generateConsigneeDeliveryAddress(TbWmsMaterialReceiptSaveParam params, String userId, String consigneeId, String warehouseId) {
        CustomerConsigneeDeliveryAddress consigneeDeliveryAddress = new CustomerConsigneeDeliveryAddress();
        consigneeDeliveryAddress.setId(idWorker.nextId() + "").preInsert(userId);
        consigneeDeliveryAddress.setCcustcode(consigneeId);
        consigneeDeliveryAddress.setAeraDesc(params.getItemList().get(0).getDestination());
        consigneeDeliveryAddress.setDeliveryAddress(params.getItemList().get(0).getConsigneeAddress());
        consigneeDeliveryAddress.setWarehouseCode(warehouseId);
        consigneeDeliveryAddress.setSeq(Long.parseLong("0"));
        consigneeDeliveryAddress.setIsValid("1");
        this.customerConsigneeDeliveryAddressMapper.insert(consigneeDeliveryAddress);
        return consigneeDeliveryAddress;
    }

    @Transactional(readOnly = false)
    public CustomerConsignee generateConsigneeId(TbWmsMaterialReceiptSaveParam params,String userId,String customerNo) {
        CustomerConsignee customerConsignee = new CustomerConsignee();
        if(!StringUtils.isNull(params.getItemList().get(0).getConsigneeNo())){
            customerConsignee.setId(params.getItemList().get(0).getConsigneeNo());
        }else{
            customerConsignee.setId(idWorker.nextId() + "").preInsert(userId);
        }
        customerConsignee.setCustomerNo(customerNo);
        customerConsignee.setAreaDesc(params.getItemList().get(0).getDestination());
        customerConsignee.setConsigneeAddress(params.getItemList().get(0).getConsigneeAddress());
        customerConsignee.setLinkManMobile(params.getItemList().get(0).getConsigneePhoneNo());
        customerConsignee.setConsigneeType(params.getCustomerType());
        customerConsignee.setConsigneeName(params.getItemList().get(0).getConsigneeName());
        customerConsignee.setId(idWorker.nextId() + "").preInsert(userId);
        this.customerConsigneeMapper.insert(customerConsignee);
        return customerConsignee;
    }

    private List<TbWmsMaterialReceiptLine> insertMaterialInLocation(List<TbWmsMaterialReceiptLine> tbWmsMaterialReceiptLines,UserVo sysUser,TbWmsMaterialReceiptSaveParam param) {
        for(int i=0; i< tbWmsMaterialReceiptLines.size();i++) {
            TbWmsMaterialReceiptLine tbWmsMaterialReceiptLine = (TbWmsMaterialReceiptLine)tbWmsMaterialReceiptLines.get(i);

            TbWmsMaterialInLocation tbWmsMaterialInLocation = new TbWmsMaterialInLocation();

            tbWmsMaterialInLocation.setLocationNo(param.getItemList().get(0).getLocationNo());

            tbWmsMaterialInLocation.setArea(param.getItemList().get(0).getAreaNo());

            tbWmsMaterialInLocation.setAreaId(tbWmsMaterialReceiptLine.getAreaNo());
        //    tbWmsMaterialInLocation.setTier(tbWmsMaterialReceiptLine.getMaterialNo());
            tbWmsMaterialInLocation.setSkuCode(tbWmsMaterialReceiptLine.getSkuCode());
       //     tbWmsMaterialInLocation.setBin(tbWmsMaterialReceiptLine.getMaterialNo());
      //      tbWmsMaterialInLocation.setBay(tbWmsMaterialReceiptLine.getMaterialNo());

        //    tbWmsMaterialInLocation.setLotNo(tbWmsMaterialReceiptLine.getMaterialNo());

       //     tbWmsMaterialInLocation.setCellNo(tbWmsMaterialReceiptLine.getMaterialNo());
            tbWmsMaterialInLocation.setCustomerId(tbWmsMaterialReceiptLine.getCustomerNo());
            tbWmsMaterialInLocation.setMaterialNo(tbWmsMaterialReceiptLine.getMaterialNo());
            tbWmsMaterialInLocation.setMaterialName(tbWmsMaterialReceiptLine.getMaterialName());
            tbWmsMaterialInLocation.setReceivedLineId(tbWmsMaterialReceiptLine.getId());
            //tbWmsMaterialInLocation.setQuantity(tbWmsMaterialReceiptLine.getQuantity().doubleValue());
            //double rate = NumberUtils.div(tbWmsMaterialReceiptLine.getQuantity().doubleValue(), tbWmsMaterialReceiptLine.getQuantity());
            /*if (tbWmsMaterialReceiptLine.getVolume() != null) {
                Double volume = NumberUtils.mul(tbWmsMaterialReceiptLine.getVolume(), rate);
                tbWmsMaterialInLocation.setVol(volume);

            }
            if (tbWmsMaterialReceiptLine.getWeight() != null) {
                Double wt = NumberUtils.mul(tbWmsMaterialReceiptLine.getWeight(), rate);
                tbWmsMaterialInLocation.setWeight(wt);

            }*/

            tbWmsMaterialInLocation.setSiteCode(tbWmsMaterialReceiptLine.getSite());
            tbWmsMaterialInLocation.setStatus(WmsInStatusEnum.inposition.getValue());
            tbWmsMaterialInLocation.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
            this.tbWmsMaterialInLocationMapper.insert(tbWmsMaterialInLocation);
            tbWmsMaterialReceiptLine.setLocationNo(tbWmsMaterialInLocation.getId());
            tbWmsMaterialReceiptLine.preUpdate(sysUser.getId());
            this.tbWmsMaterialReceiptLineMapper.updateById(tbWmsMaterialReceiptLine);

        }
        return tbWmsMaterialReceiptLines;
    }

    @Transactional(readOnly = false)
    @Override
    public  String insertInLocation(TbWmsMaterialReceiptSaveParam params, String receiptId, UserVo sysUser, List<TbWmsMaterialReceiptLine> tbWmsMaterialReceiptLines) {
       for(int i=0; i< tbWmsMaterialReceiptLines.size();i++) {
            TbWmsMaterialReceiptLine tbWmsMaterialReceiptLine = (TbWmsMaterialReceiptLine)tbWmsMaterialReceiptLines.get(i);
            tbWmsMaterialReceiptLine.setStatus(WmsInStatusEnum.inposition.getValue());
           tbWmsMaterialReceiptLine.setReceiptType("tool");
            tbWmsMaterialReceiptLine.preUpdate(sysUser.getId());

            this.tbWmsMaterialReceiptLineMapper.updateById(tbWmsMaterialReceiptLine);

            TbWmsMaterialInLocation tbWmsMaterialInLocation = new TbWmsMaterialInLocation();
            tbWmsMaterialInLocation.setLocationNo(tbWmsMaterialReceiptLine.getMaterialNo());
          //  tbWmsMaterialInLocation.setArea(tbWmsMaterialReceiptLine.getMaterialNo());
         //   tbWmsMaterialInLocation.setTier(tbWmsMaterialReceiptLine.getMaterialNo());
         //   tbWmsMaterialInLocation.setSkuCode(tbWmsMaterialReceiptLine.getSkuCode());
         //   tbWmsMaterialInLocation.setBin(tbWmsMaterialReceiptLine.getMaterialNo());
        //    tbWmsMaterialInLocation.setBay(tbWmsMaterialReceiptLine.getMaterialNo());
       //     tbWmsMaterialInLocation.setLotNo(tbWmsMaterialReceiptLine.getMaterialNo());
      //      tbWmsMaterialInLocation.setCellNo(tbWmsMaterialReceiptLine.getMaterialNo());
           tbWmsMaterialInLocation.setSkuCode("tool");
           tbWmsMaterialInLocation.setWarehouseCode(params.getWarehouseCode());
           tbWmsMaterialInLocation.setArea(tbWmsMaterialReceiptLine.getCustomerName());
            tbWmsMaterialInLocation.setCustomerId(tbWmsMaterialReceiptLine.getCustomerNo());
            tbWmsMaterialInLocation.setMaterialNo(tbWmsMaterialReceiptLine.getMaterialNo());
            tbWmsMaterialInLocation.setMaterialName(tbWmsMaterialReceiptLine.getMaterialName());
            tbWmsMaterialInLocation.setReceivedLineId(tbWmsMaterialReceiptLine.getId());
            SkuVo sku = this.skuMapper.findById(tbWmsMaterialReceiptLine.getMaterialNo());
            if(sku!=null){
                if(sku.getQty()!=null){
                    Double quantity = NumberUtils.mul(tbWmsMaterialReceiptLine.getQuantity().doubleValue(),sku.getQty());
                    tbWmsMaterialInLocation.setQuantity(quantity);
                }else{
                    tbWmsMaterialInLocation.setQuantity(tbWmsMaterialReceiptLine.getQuantity().doubleValue());
                }
            }else{
                tbWmsMaterialInLocation.setQuantity(tbWmsMaterialReceiptLine.getQuantity().doubleValue());
            }

            double rate = NumberUtils.div(tbWmsMaterialReceiptLine.getQuantity().doubleValue(), tbWmsMaterialReceiptLine.getQuantity());
            if (tbWmsMaterialReceiptLine.getVolume() != null) {
                Double volume = NumberUtils.mul(tbWmsMaterialReceiptLine.getVolume(), rate);
                tbWmsMaterialInLocation.setVol(volume);

            }
            if (tbWmsMaterialReceiptLine.getWeight() != null) {
                Double wt = NumberUtils.mul(tbWmsMaterialReceiptLine.getWeight(), rate);
                tbWmsMaterialInLocation.setWeight(wt);

            }

            tbWmsMaterialInLocation.setSiteCode(tbWmsMaterialReceiptLine.getSite());
            tbWmsMaterialInLocation.setStatus(WmsInStatusEnum.inposition.getValue());
            tbWmsMaterialInLocation.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
            this.tbWmsMaterialInLocationMapper.insert(tbWmsMaterialInLocation);
        }
        return "SUCCESS";
    }
    @Transactional(readOnly = false)
    @Override
    public String insertALLToolsItem(TbWmsMaterialReceiptSaveParam params){
        // 收货人编码为空时，新增收货人
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        if(StringUtils.isNull(params.getCustomerNo())) {
            String customerNo = this.generateCustomer(params,sysUser.getId());
            params.setCustomerNo(customerNo);
        }

        // 新增运单主表信息
        if(StringUtils.isNull(params.getOrderNo())){
            String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialReceipt");
            params.setOrderNo("R".concat(orderNo));
        }

        params.setSiteCode(sysUser.getSite())
                .setStatus(WmsInStatusEnum.created.getValue());




        String receiptId = this.insert(params);
        // 新增运单明细信息
        List<TbWmsMaterialReceiptLine> tbWmsMaterialReceiptLines= insertItem(params, receiptId,sysUser);
        insertInLocation(params, receiptId,sysUser,tbWmsMaterialReceiptLines);

        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String insertALLItem(TbWmsMaterialReceiptSaveParam params){
        // 收货人编码为空时，新增收货人
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        if(StringUtils.isNull(params.getCustomerNo())) {
            String customerNo = this.generateCustomer(params,sysUser.getId());
            params.setCustomerNo(customerNo);
        }

        // 新增运单主表信息
       if(StringUtils.isNull(params.getOrderNo())){
           String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialReceipt");
           params.setOrderNo("R".concat(orderNo));
       }

        params.setSiteCode(sysUser.getSite())
                .setStatus(WmsInStatusEnum.created.getValue());




        String receiptId = this.insert(params);
        // 新增运单明细信息
        List<TbWmsMaterialReceiptLine> lines= insertItem(params, receiptId,sysUser);

        return "success";
    }

    @Transactional(readOnly = false)
    @Override
    public int updataNewVehicleReceipt(TbWmsMaterialReceiptSaveParam params){
        TbWmsMaterialReceiptLineSaveParam t = new TbWmsMaterialReceiptLineSaveParam();
        BeanUtils.copyProperties(params.getItemList().get(0), t);
        //保存明细
        iTbWmsMaterialReceiptLineService.update(t);

        TbWmsMaterialReceipt entity = new TbWmsMaterialReceipt();
        BeanUtils.copyProperties(params, entity);

        return mapper.updateById(entity);
    }
    @Transactional(readOnly = false)
    @Override
    public String generateCustomer(TbWmsMaterialReceiptSaveParam params,String userId) {
        Customer entity = new Customer();
        String CustomerCode = tBmsAllGeneralSeqTabService.generateNo("CustomerCode");
        entity.setId(idWorker.nextId() + "")
                .preInsert(userId);
        entity.setCustomerCode("C".concat(CustomerCode));
        entity.setCity(params.getConsignmentLocation());
        entity.setCustomerType(params.getCustomerType());
        entity.setAddress(params.getShipperAddress());
        entity.setCompanyName(params.getCustomerName());
        entity.setContactName(params.getShipperContact());
        entity.setContactPhone(params.getShipperPhoneNo());
        entity.setCustomerName(params.getCustomerName());
        this.customerMapper.insert(entity);
        return entity.getId();
    }
    @Transactional(readOnly = false)
    @Override
    public  List<TbWmsMaterialReceiptLine> insertItem(TbWmsMaterialReceiptSaveParam params, String receiptId,UserVo sysUser) {
        List<TbWmsMaterialReceiptLine> tbWmsMaterialReceiptLines = new ArrayList<TbWmsMaterialReceiptLine>();
        if(ListUtils.isNotEmpty(params.getItemList())){
            int itemNo = 1;

            for (TbWmsMaterialReceiptLineSaveParam item : params.getItemList()) {
                if(StringUtils.isNull(item.getShipByPackOrqty())){
                    item.setShipByPackOrqty(MaterialBaseOnEnum.weight.getValue());
                }


               /* if (MaterialBaseOnEnum.weight.getValue().equals(item.getShipByPackOrqty())) {
                    if (item.getWeight() == null) {
                        throw new BusinessException("计量单位为重量时，总重不能为空");
                    }
                }
                if (MaterialBaseOnEnum.vol.getValue().equals(item.getShipByPackOrqty())) {
                    if (item.getVolume() == null) {
                        throw new BusinessException("计量单位为体积时，总体积不能为空");
                    }
                }
                if (MaterialBaseOnEnum.pack.getValue().equals(item.getShipByPackOrqty())) {
                    if (item.getQuantity() == null) {
                        throw new BusinessException("计量单位为数量时，总数量不能为空");
                    }
                }
                if (MaterialBaseOnEnum.qty.getValue().equals(item.getShipByPackOrqty())) {
                    if (item.getPackQty() == null) {
                        throw new BusinessException("计量单位为包装件数时，总件数不能为空");
                    }
                }*/
                item.setReceiptId(receiptId)
                        .setSkuCode(item.getSkuCode())
                        .setOrderNo(params.getOrderNo())
                        .setCustomerNo(params.getCustomerNo())
                        .setCustomerName(params.getCustomerName())
                        .setBatchNo(params.getSourceOrderNo())
                        //.setStageNo(params.getStageNo())
                        //    .setMaterialName(params.getMaterialName())
                        //    .setMaterialNo(params.getShippingTime())
                        //  .setQtyPerPack(params.getCarrierTime())
                        //.setQuantity(item.getCustShipByQty())
                        //       .setCountPrice(new BigDecimal(0.0))
                        //     .setCountTotalPrice(String.valueOf(itemNo++))
                        .setStatus(params.getStatus())
                        .setLineNo(Long.valueOf(itemNo++))
                        //  .setVolume(params.getCompanyNo())
                        //            .setUnitVolume(params.getConsigneeAddress())
                        //            .setUnitWeight(params.getConsigneeName())
                        //            .setWeight(params.getShipperName())
                        .setSite(params.getSiteCode());
                //         .setLength(item.getVehicleModelNo())
                //         .setWidth(item.getVehicleModelNo())
                //          .setHigh(item.getVehicleModelNo())
                //          .setHighMeasUnit(params.getServiceType())
                //          .setWeightMeasUnit(params.getServiceType())
                //          .setMeasUnitNo(item.getShipByPackOrqty());

                if(!StringUtils.isNull(sysUser.getCustomerId())){
                    item.setCompanyNo(sysUser.getCustomerId());
                }else  if(!StringUtils.isNull(sysUser.getSupplierId())){
                    item.setCompanyNo(sysUser.getSupplierId());
                }else if(!StringUtils.isNull(sysUser.getBaoliCompanyId())){
                    item.setCompanyNo(sysUser.getBaoliCompanyId());
                }else if(!StringUtils.isNull(sysUser.getStoreId())){
                    item.setCompanyNo(sysUser.getStoreId());
                }else{
                    item.setCompanyNo(sysUser.getOrgId());
                }
                TbWmsMaterialReceiptLine  tbWmsMaterialReceiptLine=  this.iTbWmsMaterialReceiptLineService.insertEntity(item);
                tbWmsMaterialReceiptLines.add(tbWmsMaterialReceiptLine);
            }
        }
        return tbWmsMaterialReceiptLines;
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(TbWmsMaterialReceiptSaveParam params) {
        TbWmsMaterialReceipt entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(sysUser.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public TbWmsMaterialReceiptVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<TbWmsMaterialReceiptVo> findAll(TbWmsMaterialReceiptSearchParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<TbWmsMaterialReceiptVo> findAll(TbWmsMaterialReceiptSearchParam params, Integer current, Integer pageSize) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }



}
